package eteam.aps.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import eteam.aps.api.U8Api;
import eteam.aps.common.component.LoginUserRedisService;
import eteam.aps.common.constant.PackType;
import eteam.aps.common.constant.ProductType;
import eteam.aps.common.constant.ScanType;
import eteam.aps.common.entity.ParentEntity;
import eteam.aps.common.helper.Helper;
import eteam.aps.mapper.MocoRdersMapper;
import eteam.aps.mapper.PackagingWarehousingMapper;
import eteam.aps.mapper.ProductNumberMapper;
import eteam.aps.mapper.ScanProcessStepMapper;
import eteam.aps.model.dto.PackagingWarehouseDto;
import eteam.aps.model.entity.MocoRders;
import eteam.aps.model.entity.PackagingWarehousing;
import eteam.aps.model.entity.ScanProcessStep;
import eteam.aps.model.vo.moco_rders.MocoRdersDisplayVo;
import eteam.aps.service.PackagingWarehousingService;
import eteam.aps.systeminterface.model.dto.VerifyTokenDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 包装入库 业务层实现类
 *
 * @author LiuLei
 */
@Service
public class PackagingWarehousingServiceImpl implements PackagingWarehousingService {

    @Autowired
    private MocoRdersMapper mocoRdersMapper;

    @Autowired
    private ScanProcessStepMapper scanProcessStepMapper;

    @Autowired
    private LoginUserRedisService loginUserRedisService;

    @Autowired
    private PackagingWarehousingMapper packagingWarehousingMapper;

    @Autowired
    private ProductNumberMapper productNumberMapper;

    @Override
    @Transactional
    public MocoRdersDisplayVo getMocoRdersPackage(String scan, Integer quteType) throws Exception {
        Map<String, Object> map = new HashMap<>(4);
        // 状态不为删除
        map.put("fState", ParentEntity.FSTATE_DELETED);
        // 当前扫描的数据
        map.put("code", scan);
        // 扫描工单？ 状态必须 为正常 报工
        map.put("start", ProductType.FINISH);
        map.put("end", ProductType.FINISH);
        // 没有进行包装扫描的数据
        map.put("packType", PackType.DEFAULT);
        MocoRdersDisplayVo moc = mocoRdersMapper.selMocByProBarCode(map);
        if (moc == null) return null;
        VerifyTokenDto user = loginUserRedisService.getUser();
        Map<String, Object> upt = new HashMap<>(4);
        upt.put("modify", user.getFuserid());
        upt.put("time", LocalDateTime.now());
        upt.put("barCode", scan);
        upt.put("packType", PackType.SCAN);
        upt.put("outerPackaging", quteType);
        productNumberMapper.updatePackType(upt);
        // 记录操作步骤
        ScanProcessStep step = new ScanProcessStep(
                moc.getFcbSysBarCode(),
                null,
                "包装入库",
                user.getFuserid(),
                user.getFfullname(),
                LocalDateTime.now(),
                ScanType.MOC,
                PackType.SCAN
        );
        Helper.setDefaultAddValue(step, user.getFuserid());
        // 记录操作步骤
        scanProcessStepMapper.addScanStep(step);
        return moc;
    }

    @Override
    public MocoRders getMocoRdersWarehousing(String scan) {
        Map<String, Object> map = new HashMap<>(4);
        // 状态不为删除
        map.put("fState", ParentEntity.FSTATE_DELETED);
        // 当前扫描的数据
        map.put("code", scan);
        // 扫描工单？ 状态必须 为正常 报工
        map.put("start", ProductType.FINISH);
        map.put("end", ProductType.FINISH);
        map.put("packType", PackType.SCAN);
        return mocoRdersMapper.selMocByProBarCodeAll(map);
    }

    @Override
    @Transactional
    public String savePackagingWarehousing(Map<String, Object> map) throws Exception {
//         u8入库
        JSONObject u8 = U8Api.formatTime(map);
        JSONArray ds = u8.getJSONArray("data");
        // todo 这里只是pts入库 并不与U8的产成品入库产生关联
//        String proIn = U8Api.ptsProIn(ds.toString());
//        if (Helper.isNotEmpty(proIn)) {
        // 本地存储
        List<PackagingWarehousing> list = new LinkedList<>();
        for (Object data : u8.getJSONArray("data")) {
            JSONObject head = (JSONObject) data;
            String cWhCode = head.getStr("cWhCode");
            String cWhName = head.getStr("cWhName");
            for (Object rows : head.getJSONArray("Rows")) {
                JSONObject row = (JSONObject) rows;
                list.add(new PackagingWarehousing(
                        row.getStr("barCode"),
                        row.getInt("iMPoIds"),
                        row.getStr("cMoCode"),
                        row.getBigDecimal("iQuantity"),
                        row.getStr("cInvCode"),
                        row.getStr("cInvName"),
                        row.getStr("cInvStd"),
                        cWhCode,
                        cWhName,
                        row.getStr("cFree1"),
                        row.getStr("cBatch")
                ));
            }
        }
        // 本地保存
        String fuserid = loginUserRedisService.getUser().getFuserid();
        list.forEach(data -> Helper.setDefaultAddValue(data, fuserid));
        packagingWarehousingMapper.batchPackagingWarehousing(list);
        // 修改产品状态 (入库)
        List<Map<String, Object>> mapList = new ArrayList<>();
        list.forEach(data -> {
            Map<String, Object> mp = new HashMap<>(6);
            mp.put("processing", ProductType.STORAGE);
            mp.put("modify", fuserid);
            mp.put("time", LocalDateTime.now());
            mp.put("bar", data.getFcbSysBarCode());
            mp.put("batch", data.getfBatch());
            mp.put("banBen", data.getfBanBenCode());
            mp.put("whCode", data.getfWhCode());
            mp.put("whName", data.getfWhName());
            mapList.add(mp);
        });
        productNumberMapper.batchUpdatePro(mapList);
//        }
        return "";
    }

    @Override
    public List<MocoRdersDisplayVo> getMocoRdersLisByQuery(PackagingWarehouseDto packagingWarehouseDto) {
        Map<String, Object> map = new HashMap<>(5);
        if (Helper.isNotEmpty(packagingWarehouseDto.getStartTime()))
            map.put("startTime", packagingWarehouseDto.getStartTime());
        if (Helper.isNotEmpty(packagingWarehouseDto.getEndTime()))
            map.put("endTime", packagingWarehouseDto.getEndTime());
        map.put("fState", ParentEntity.FSTATE_DELETED);
        int type = packagingWarehouseDto.getType();
        if (type == ProductType.DRAFT) {
            // 包装
            map.put("fPackType", PackType.SCAN);
            map.put("start", ProductType.ERROR);
            map.put("end", ProductType.FINISH);
        } else {
            // 入库
            map.put("start", ProductType.STORAGE);
            map.put("end", ProductType.STORAGE);
        }
        return mocoRdersMapper.getMocoRdersLisByQuery(map);
    }

    @Override
    public Map<String, Integer> getMocoRdersPackageScanSummary(String scan) {
        String mocCode = productNumberMapper.selMocByBarCode(scan, ParentEntity.FSTATE_DELETED);
        if (mocCode != null) {
            int[] list = productNumberMapper.selMocSummary(mocCode, PackType.DEFAULT);
            Map<String, Integer> map = new HashMap<>(3);
            map.put("all", list[0] + list[1]);
            map.put("already", list[0]);
            map.put("without", list[1]);
            return map;
        }
        return Collections.emptyMap();
    }

    @Override
    @Transactional
    public int updatePackagePackType(String scan) throws Exception {
        Map<String, Object> upt = new HashMap<>(4);
        upt.put("modify", loginUserRedisService.getUser().getFuserid());
        upt.put("time", LocalDateTime.now());
        upt.put("barCode", scan);
        upt.put("packType", PackType.DEFAULT);
        return productNumberMapper.updatePackType(upt);
    }

}
